/*
 * Niiuzu
 * Copyright (C) 2011  Thierry Nowak
 * 
 * This program is free software: you can redistribute it and/or modify it under
 * the terms of the GNU General Public License as published by the Free Software
 * Foundation, either version 3 of the License, or (at your option) any later
 * version.
 * 
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
 * details.
 * 
 * You should have received a copy of the GNU General Public License along with
 * this program.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.niiuzu.client.screen.channel.manager;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.HasValue;
import com.google.inject.Inject;
import com.mvp4g.client.annotation.Presenter;
import com.mvp4g.client.presenter.LazyPresenter;
import com.niiuzu.client.eventbus.FeedEventBus;
import com.niiuzu.client.screen.channel.manager.ChannelManagerView.AddChannelResult;
import com.niiuzu.client.util.SessionClient;
import com.niiuzu.client.util.callback.AbstractCallback;
import com.niiuzu.shared.model.RssChannel;
import com.niiuzu.shared.rpc.FeedServiceAsync;

/**
 * Presenter dédié à la gestion des flux RSS.
 */
@Presenter(view = ChannelManagerViewImpl.class)
public class ChannelManagerPresenter extends
		LazyPresenter<ChannelManagerView, FeedEventBus> {

	@Inject
	private FeedServiceAsync feedService;

	private ClickHandler addNewChannelClickHandler;

	private ClickHandler lastRemoveClickHandler;

	@Override
	public void bindView() {
		super.bindView();

		addNewChannelClickHandler = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				HasValue<String> hasLinkValue;
				hasLinkValue = view.getLinkNewChannelHasValue();

				String channelLink = hasLinkValue.getValue();

				// RAZ de la valeur à l'écran
				hasLinkValue.setValue("");

				feedService.createChannelFromLink(channelLink,
						new AbstractCallback<RssChannel>(eventBus) {
							@Override
							public void onSuccess(RssChannel result) {
								recoverNewChannel(result);
							}
						});
			}
		};
		view.getAddNewChannelHasClickHandlers().addClickHandler(
				addNewChannelClickHandler);
	}

	/**
	 * Chargement de la vue sur la gestion des flux RSS.
	 * 
	 * @see FeedEventBus#channelManagerLoadStarted()
	 */
	public void onChannelManagerLoadStarted() {

		// Ajout de flux par défaut dès l'arrivée sur l'écran
		if (SessionClient.getInstance().getChannelMap().isEmpty()) {
			RssChannel channel;
			// TODO Revoir la gestion de ces identifiants
			int i = 1000;

			// Le Monde
			channel = new RssChannel();
			channel.setId(i++);
			channel.setName("Le Monde");
			channel.setLink("http://www.lemonde.fr/rss/une.xml");
			addAndBindChannel(channel);

			// l'Equipe
			channel = new RssChannel();
			channel.setId(i++);
			channel.setName("L'Equipe");
			channel.setLink("http://www.lequipe.fr/Xml/actu_rss.xml");
			addAndBindChannel(channel);

			// Clubic
			channel = new RssChannel();
			channel.setId(i++);
			channel.setName("Clubic");
			channel.setLink("http://www.clubic.com/articles.rss");
			addAndBindChannel(channel);
		}

		eventBus.channelManagerLoaded(view);
	}

	/**
	 * Retourne le comportement d'un clic sur le bouton d'ajout de flux.
	 */
	public ClickHandler getAddNewChannelClickHandler() {
		return addNewChannelClickHandler;
	}

	/**
	 * Récupération du flux créé suite à un clic sur le bouton "ajouter".
	 */
	void recoverNewChannel(RssChannel channel) {
		addAndBindChannel(channel);

		eventBus.channelListUpdated();
	}

	/**
	 * Ajoute un flux dans la liste et affecte les comportements aux composants
	 * créés.
	 */
	void addAndBindChannel(final RssChannel channel) {
		SessionClient.getInstance().addChannel(channel);

		AddChannelResult result = view.addChannel(channel.getName());

		// Bind de la suppression
		final Integer rowIndex = result.getRowIndex();
		lastRemoveClickHandler = new ClickHandler() {
			@Override
			public void onClick(ClickEvent event) {
				SessionClient.getInstance().removeChannel(channel);
				view.removeChannel(rowIndex);
				eventBus.channelListUpdated();
			}
		};
		result.getHasClickHandlers().addClickHandler(lastRemoveClickHandler);
	}

	/**
	 * Comportement affecté au dernier bouton de suppression de flux ajouté.
	 */
	ClickHandler getLastRemoveClickHandler() {
		return lastRemoveClickHandler;
	}

	/* ********************************************************************** */
	/* ********************************************************************** */
	/* ********************************************************************** */

	/**
	 * JUnit - Définit un mock pour {@link FeedServiceAsync}.
	 */
	void setMockFeedService(FeedServiceAsync feedService) {
		this.feedService = feedService;
	}

}
